<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" icon="el-icon-circle-check" size="small" v-if="permission.openingInspectionConfig_enable && row.status == 2" @click="handleEnable(row.id)"
          >启用</el-button
        >
        <el-button type="text" icon="el-icon-circle-close" size="small" v-if="permission.openingInspectionConfig_disable && row.status == 1" @click="handleDisable(row.id)"
          >禁用</el-button
        >
        <el-button type="text" size="small" icon="el-icon-view" @click="viewConfig(row, 'view')">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.openingInspectionConfig_edit" @click="viewConfig(row, 'edit')">编辑</el-button>
        <el-button size="small" type="text" icon="el-icon-delete" v-if="permission.openingInspectionConfig_detail" @click="deleteConfig(row)">删除</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.openingInspectionConfig_add" @click="addConfig()">新 增</el-button>
        <el-button size="small" type="danger" icon="el-icon-delete" v-if="permission.openingInspectionConfig_detail" @click="handleDelete()">删 除</el-button>
      </template>
    </avue-crud>
    <el-dialog :title="dialogTitle" append-to-body :visible.sync="showDialog" @close="closeDialog" :fullscreen="true">
      <div class="groups">
        <div class="titleIcon">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h4>基本信息</h4>
        </div>
      </div>
      <avue-form ref="basicInfoForm" v-show="showDialog" v-model="basicInfoForm" :option="basicInfoOption"></avue-form>
      <div class="groups">
        <div class="titleIcon">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h4>适用生产工段</h4>
        </div>
      </div>
      <avue-crud v-if="showDialog" ref="workSectionRecordCrud" :option="workSectionRecordOption" :data="workSectionRecordData">
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" :disabled="dialogTitle === '查看'" @click="handleAddWorkSection">新增生产工段</el-button>
        </template>
        <template slot-scope="{ index }" slot="menu">
          <el-button icon="el-icon-delete" size="small" type="text" @click="workSectionRecordDel(index)">删除</el-button>
        </template>
      </avue-crud>
      <div class="groups">
        <div class="titleIcon">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h4>检验项</h4>
        </div>
      </div>
      <p>一、检查类型：物料</p>
      <el-row :gutter="30" style="line-height: 40px" v-for="(item, index) in inspectionTypeByMaterial" :key="index">
        <el-col :span="1" style="text-align: right">{{ index + 1 }}</el-col>
        <el-col :span="10">
          <el-input v-model="item.description" readonly></el-input>
        </el-col>
        <el-col :span="13"> 启用：<el-switch v-model="item.enabled" active-text="是" inactive-text="否" :disabled="dialogTitle === '查看'"></el-switch></el-col>
      </el-row>
      <p>二、检查类型：设备</p>
      <el-row :gutter="30" style="line-height: 40px" v-for="(item, index) in inspectionTypeByEquipment" :key="index">
        <el-col :span="1" style="text-align: right">{{ index + 1 }}</el-col>
        <el-col :span="10">
          <el-input v-model="item.description" readonly></el-input>
        </el-col>
        <el-col :span="13"> 启用：<el-switch v-model="item.enabled" active-text="是" inactive-text="否" :disabled="dialogTitle === '查看'"></el-switch></el-col>
      </el-row>
      <p>三、检查类型：人员</p>
      <el-row :gutter="30" style="line-height: 40px" v-for="(item, index) in inspectionTypeByPeople" :key="index">
        <el-col :span="1" style="text-align: right">{{ index + 1 }}</el-col>
        <el-col :span="10">
          <el-input v-model="item.description" readonly></el-input>
        </el-col>
        <el-col :span="13"> 启用：<el-switch v-model="item.enabled" active-text="是" inactive-text="否" :disabled="dialogTitle === '查看'"></el-switch></el-col>
      </el-row>
      <div slot="footer">
        <el-button size="small" type="primary" v-if="dialogTitle != '查看'" @click="handleSubmit()"><i class="el-icon-circle-plus-outline"></i><span>提 交</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </div>
    </el-dialog>
    <!--公用模态弹框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, add, remove, enable } from '@/api/product/openingInspectionConfig';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import { getQmsTemplateFile } from '@/api/resource/attach';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { exprot, getExprot } from '@/api/repair/failureconfig';
export default {
  components: {
    userTableConfig,
    commonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      fullscreenDialog: false, //dialog是否全屏
      form: {},
      model: {},
      loading: true,
      downLoadVisible: false,
      templateList: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      checkIqc: true,
      option: {
        height: 'calc(100vh - 436px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        searchLabelWidth: 90,
        menuWidth: 250,
        columnBtn: false,
        column: [
          {
            label: '检查名称',
            prop: 'name',
            search: true
          },
          {
            label: '生产工段',
            prop: 'sectionName'
          },
          {
            label: '更新人',
            prop: 'updateUserName'
          },
          {
            label: '最新更新时间',
            prop: 'updateTime'
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicData: [
              { label: '启用', value: 1 },
              { label: '禁用', value: 2 }
            ]
          }
        ]
      },
      showDialog: false,
      dialogTitle: '新增',
      basicInfoForm: {},
      basicInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '检查名称',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入检查名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检查编码',
            prop: 'code',
            disabled: true
          }
        ]
      },
      workSectionRecordData: [],
      workSectionRecordOption: {
        height: '300',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        menu: true,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '生产工段',
            prop: 'sectionName'
          },
          {
            label: '工段编码',
            prop: 'sectionCode'
          }
        ]
      },
      tableOption: {},
      inspectionTypeByMaterial: [
        { code: 'SMT_FEEDING_CHECK', description: 'SMT上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'AI_FEEDING_CHECK', description: 'AI上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'WORKORDER_FEEDING_CHECK', description: '工单上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'PRE_PROCESS_CHECK', description: '前加工已完成？', enabled: false, type: 'MATERIAL' }
      ],
      inspectionTypeByEquipment: [
        { code: 'EQUIPMENT_CHECK', description: '设备状态为正常？', enabled: false, type: 'EQUIPMENT' },
        { code: 'FIXTURE_STATUS_CHECK', description: '工装夹具状态已采集？', enabled: false, type: 'EQUIPMENT' }
      ],
      inspectionTypeByPeople: [{ code: 'SHIFT_REGISTER_CHECK', description: '已进行班组登记？', enabled: false, type: 'HUMAN' }]
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.data = data.records;
        let sectionNameList = [];
        this._forEach(this.data, (item) => {
          sectionNameList = [];
          this._forEach(item.configSections, (sectionItem) => {
            sectionNameList.push(sectionItem.sectionName);
          });
          item['sectionName'] = sectionNameList.join('，');
        });
        this.page.total = data.total;
        this.loading = false;
      });
    },
    addConfig() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = false;
      });
      this.workSectionRecordOption.menu = true;
    },
    handleAddWorkSection() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '新增生产工段',
        url: '/api/mes-product/section/page',
        isPage: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '生产工段',
            prop: 'name',
            search: true
          },
          {
            label: '工段编码',
            prop: 'code'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      let list = this._map(rowData, (item) => {
        return {
          sectionId: item.id,
          sectionCode: item.code,
          sectionName: item.name
        };
      });
      this.workSectionRecordData = [...this._cloneDeep(this.workSectionRecordData), ...list];
    },
    workSectionRecordDel(index) {
      this.workSectionRecordData.splice(index, 1);
    },
    handleSubmit() {
      if (this.workSectionRecordData.length === 0) {
        this.$message.warning('请新增生产工段！');
        return;
      }
      let params = {
        name: this.basicInfoForm.name,
        configItems: [...this.inspectionTypeByMaterial, ...this.inspectionTypeByEquipment, ...this.inspectionTypeByPeople],
        status: this.dialogTitle === '新增' ? 1 : this.basicInfoForm.status
      };
      if (this.dialogTitle === '编辑') {
        params['id'] = this.basicInfoForm.id;
      }
      let configSections = this._map(this.workSectionRecordData, (item) => {
        return {
          sectionId: item.sectionId,
          sectionCode: item.sectionCode,
          sectionName: item.sectionName
        };
      });
      params['configSections'] = configSections;
      console.log(params);
      add(params).then((res) => {
        this.showDialog = false;
        this.$message.success(res.data.msg);
        this.onLoad(this.page);
      });
    },
    closeDialog() {
      this.$refs.basicInfoForm.resetFields();
      this.basicInfoForm = {};
      this.workSectionRecordData = [];
      this.inspectionTypeByMaterial = [
        { code: 'SMT_FEEDING_CHECK', description: 'SMT上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'AI_FEEDING_CHECK', description: 'AI上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'WORKORDER_FEEDING_CHECK', description: '工单上料已完成？', enabled: false, type: 'MATERIAL' },
        { code: 'PRE_PROCESS_CHECK', description: '前加工已完成？', enabled: false, type: 'MATERIAL' }
      ];
      this.inspectionTypeByEquipment = [
        { code: 'EQUIPMENT_CHECK', description: '设备状态为正常？', enabled: false, type: 'EQUIPMENT' },
        { code: 'FIXTURE_STATUS_CHECK', description: '工装夹具状态已采集？', enabled: false, type: 'EQUIPMENT' }
      ];
      this.inspectionTypeByPeople = [{ code: 'SHIFT_REGISTER_CHECK', description: '已进行班组登记？', enabled: false, type: 'HUMAN' }];
    },
    viewConfig(row, type) {
      this.showDialog = true;
      if (type === 'view') {
        this.dialogTitle = '查看';
        this.$nextTick(() => {
          this.$refs.basicInfoForm.allDisabled = true;
        });
        this.workSectionRecordOption.menu = false;
      } else {
        this.dialogTitle = '编辑';
        this.$nextTick(() => {
          this.$refs.basicInfoForm.allDisabled = false;
        });
        this.workSectionRecordOption.menu = true;
      }
      this.basicInfoForm.id = row.id;
      this.basicInfoForm.code = row.code;
      this.basicInfoForm.name = row.name;
      this.basicInfoForm.status = row.status;
      this.workSectionRecordData = row.configSections;
      this._forEach(row.configItems, (item) => {
        this._forEach(this.inspectionTypeByMaterial, (materialItem) => {
          if (item.code === materialItem.code) {
            materialItem.enabled = item.enabled;
          }
        });
        this._forEach(this.inspectionTypeByEquipment, (equipmentItem) => {
          if (item.code === equipmentItem.code) {
            equipmentItem.enabled = item.enabled;
          }
        });
      });
    },
    deleteConfig(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = this.ids.split(',');
          return remove(ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleEnable(id) {
      enable(id)
        .then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.onLoad(this.page);
        })
        .catch((err) => {});
    },
    handleDisable(id) {
      enable(id)
        .then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.onLoad(this.page);
        })
        .catch((err) => {});
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}
.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
  ::v-deep .el-form-item__label {
    font-weight: bold;
    font-size: 16px;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
::v-deep .urgent-select-row {
  color: red;
}
.groups {
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #dedede;
  .titleIcon {
    display: flex;
    align-items: center;
  }
}
.aqlValueDialog {
  ::v-deep .el-form-item__content {
    line-height: 33px;
  }
}

.title-result {
  display: flex;
  justify-content: space-between;
  .title {
    display: flex;
    align-items: center;
  }
  .reslut-btn-group {
    margin-right: 8px;
  }
}
.download-box {
  .dowload-item {
    margin: 4px 8px;
    color: #007dff;
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer/Edge */
    user-select: none;
    &:hover {
      cursor: pointer;
    }
  }
}
</style>
